/*
 * Copyright 2020-2030 ALPHA LAB.Inc All Rights Reserved.
 */
package com.alpahlab.moolight.demo.filter;

import java.io.IOException;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import com.alphalab.framework.log.IMoLog;
import com.alphalab.framework.log.MoLogFactory;
import com.alphalab.framework.util.SpringUtil;
import com.alphalab.moonlight.demo.dao.model.VisitCount;
import com.alphalab.moonlight.demo.dao.service.IVisitCountDao;

/**
 * 用户访问统计过滤器.
 * @author allen
 * @version 1.0.0 2020年4月5日
 */
@WebFilter(filterName = "VisitCountFilter",urlPatterns = {"/airlineView.html"})
public class VisitCountFilter implements Filter {
	
	/**
	 * logger.
	 */
	private static final IMoLog logger = MoLogFactory.getLog(VisitCountFilter.class);
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String ip = getIPAddress(httpRequest);
		logger.info("ip={0}", ip);
		String agent = httpRequest.getHeader("user-agent");
		logger.info("agent={0}", agent);
		VisitCount visitCount = new VisitCount();
		visitCount.setIp(ip);
		visitCount.setAgent(agent);
		visitCount.setCreateTime(new Date());
		try {
			IVisitCountDao visitCountDao = (IVisitCountDao) SpringUtil.getBean("visitCountDao");
			visitCountDao.save(visitCount);
		} catch (Exception ex) {
			logger.error("保存访问记录失败", ex);
		}
		logger.info("保存访问记录结束");
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void destroy() {
	}
	
	/**
	 * 获取实际IP地址.
	 * @param request HttpServletRequest
	 * @return String
	 */
	private static String getIPAddress(HttpServletRequest request) {
	    String ip = null;
	    //X-Forwarded-For：Squid 服务代理
	    String ipAddresses = request.getHeader("X-Forwarded-For");
	    if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
	        //Proxy-Client-IP：apache 服务代理
	        ipAddresses = request.getHeader("Proxy-Client-IP");
	    }
	    if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
	        //WL-Proxy-Client-IP：weblogic 服务代理
	        ipAddresses = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
	        //HTTP_CLIENT_IP：有些代理服务器
	        ipAddresses = request.getHeader("HTTP_CLIENT_IP");
	    }
	    if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
	        //X-Real-IP：nginx服务代理
	        ipAddresses = request.getHeader("X-Real-IP");
	    }
	    //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
	    if (ipAddresses != null && ipAddresses.length() != 0) {
	        ip = ipAddresses.split(",")[0];
	    }
	    //还是不能获取到，最后再通过request.getRemoteAddr();获取
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
	        ip = request.getRemoteAddr();
	    }
	    return ip;
	}

}
